package org.hiucung.orangeappupdater.updater.ui;

import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentActivity;

import org.hiucung.orangeappupdater.R;
import org.hiucung.orangeappupdater.updater.AppUpdater;
import org.hiucung.orangeappupdater.updater.bean.DownloadBean;
import org.hiucung.orangeappupdater.updater.net.INetDownloadCallBack;
import org.hiucung.orangeappupdater.updater.utils.AppUtils;
import org.jetbrains.annotations.NotNull;

import java.io.File;

/***
 * 应用内更新对话框
 * 当用户点击框外时，对话框是关闭状态的。但是下载并没有结束。当安装页面弹出时则会报空指针异常
 * 我们还需要做任务的中断下载
 */
public class UpdateVersionShowDialog extends DialogFragment {

    private static final String KEY_DOWNLOAD_BEAN = "download_bean";

    private DownloadBean mDownloadBean;

    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //获取数据源
        Bundle arguments = getArguments();
        if (arguments != null) {
            mDownloadBean = (DownloadBean) arguments.getSerializable(KEY_DOWNLOAD_BEAN);
        }
    }

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_updater,container,false);
        bindEvents(view);
        return view;
    }

    //在视图创建之前我们把背景透明


    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    }

    private void bindEvents(View view) {
        TextView tvTitle = view.findViewById(R.id.popup_update_appName);
        TextView tvContent = view.findViewById(R.id.popup_update_appDes);
        TextView tvUpdater = view.findViewById(R.id.tv_connect_yes);

        tvTitle.setText(mDownloadBean.title);
        tvContent.setText(mDownloadBean.content);
        tvUpdater.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setEnabled(false);
                File targetFile = new File(getActivity().getCacheDir(),"target.apk");

                //判断这个版本是否已经下载过，且MD5值与服务端相等，则直接安装
                if (targetFile.exists() && AppUtils.getFileMd5(targetFile).equals(mDownloadBean.md5)){
                    Toast.makeText(getActivity(), "安装包已存在，直接安装", Toast.LENGTH_SHORT).show();
                    AppUtils.installApk(getActivity(),targetFile);
                    return;
                }

                AppUpdater.getInstance().getNetManager().download(mDownloadBean.url, targetFile, new INetDownloadCallBack() {
                    @Override
                    public void success(File apkFile) {
                        //安装的代码
                        v.setEnabled(true);
                        Log.d("hiucung","success = "+ apkFile.getAbsolutePath());
                        dismiss();

                        //check md5
                        String fileMd5 = AppUtils.getFileMd5(targetFile);

                        Log.d("hiucung","md5 = " + fileMd5);

                        //md5校验，如果校验一致才触发安装
                        if (fileMd5 !=null && fileMd5.equals(mDownloadBean.md5)){
                            AppUtils.installApk(getActivity(),apkFile);
                        }else {
                            Toast.makeText(getActivity(),"md5 检测失败",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void progress(int progress) {
                        //更新界面进度的代码
                        Log.d("hiucung","progress = "+ progress);
                        tvUpdater.setText(progress+"%");
                    }

                    @Override
                    public void failed(Throwable throwable) {
                        v.setEnabled(true);
                        Toast.makeText(getActivity(),"文件下载失败",Toast.LENGTH_SHORT).show();
                    }
                },UpdateVersionShowDialog.this);
            }
        });
    }

    @Override
    public void onDismiss(@NonNull @NotNull DialogInterface dialog) {
        super.onDismiss(dialog);
        Log.d("hiucung","onDismiss");
        AppUpdater.getInstance().getNetManager().cancel(this);
    }

    //启动dialog，传递bean过去
    public static void show(FragmentActivity activity, DownloadBean bean){
        Bundle bundle = new Bundle();
        bundle.putSerializable(KEY_DOWNLOAD_BEAN,bean);
        UpdateVersionShowDialog dialog = new UpdateVersionShowDialog();
        dialog.setArguments(bundle);

        dialog.show(activity.getSupportFragmentManager(),"updateVersionShowDialog");
    }
}
